package com.yunxi.service.localService.impl.otd;

import com.alibaba.fastjson.JSONObject;
import com.yunxi.bizToBaseData.service.Biz2BaseVehicleConfigDubboService;
import com.yunxi.bizToHub.pojo.MonthPlanDataVO;
import com.yunxi.bizToHub.pojo.MonthPlanVO;
import com.yunxi.bizToHub.pojo.OtdModelVO;
import com.yunxi.core.service.ServiceImplPlus;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.util.DateUtil;
import com.yunxi.dao.otd.OtdOrderCirMapper;
import com.yunxi.model.otd.OtdOrderCir;
import com.yunxi.model.otd.VehicleConfigConstraint;
import com.yunxi.otd.pojo.OtdOrderCirScheduleQueryVO;
import com.yunxi.otd.pojo.OtdOrderCirVO;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.VehicleProductViewService;
import com.yunxi.service.localService.otd.OtdOrderCirService;
import com.yunxi.service.localService.otd.OtdProduceCalendarService;
import com.yunxi.service.localService.otd.VehicleConfigConstraintService;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * <p>
 * CIR生产订单 服务实现类
 * </p>
 *
 * @author XUQI
 * @since 2019-07-15
 */
@Service
public class OtdOrderCirServiceImpl extends ServiceImplPlus<OtdOrderCirMapper, OtdOrderCir> implements
    OtdOrderCirService {

    @Autowired
    @Qualifier("vehicleProductViewServiceImpl")
    VehicleProductViewService productService;

    @Autowired
    @Qualifier("otdProduceCalendarServiceImpl")
    OtdProduceCalendarService calendarService;


    @Autowired
    @Qualifier("codeCreateServiceImpl")
    CodeCreateService code;


    @Autowired
    @Qualifier("vehicleConfigConstraintServiceImpl")
    VehicleConfigConstraintService configConstraintService;

    @Autowired
    Biz2BaseVehicleConfigDubboService biz2baseVehicleConfigDubboService;

    @Override
    public OtdOrderCirVO findCirOrderSchedule(OtdOrderCirScheduleQueryVO queryVO) {
        Map map = BeanTools.bean2map(queryVO);
        String year = queryVO.getYearMonth().substring(0, 4);
        String month = queryVO.getYearMonth().substring(4, 6);
        map.put("days", DateUtil.getDayListByMonth(Integer.valueOf(year), Integer.valueOf(month)));
//        map.put("pageNum", pageNum);
//        map.put("pageSize", pageSize);
//        PageHelperPlus.startPage(pageNum,pageSize);
//        List<Map<String, Object>> list = baseMapper.findCirOrderSchedule(map);
        OtdOrderCirVO data = new OtdOrderCirVO();
        data.setTotal(baseMapper.findCirOrderScheduleCount(map));
        data.setList(baseMapper.findCirOrderSchedule(map));
        return data;
    }

    /**
     * 分页查询月cir分周排程订单
     *
     * @param queryVO 查询VO
     * @return 分页对象
     */
    @Override
    public OtdOrderCirVO findMonthCirWeekly(OtdOrderCirScheduleQueryVO queryVO) {
        Map map = BeanTools.bean2map(queryVO);
        String year = queryVO.getYearMonth().substring(0, 4);
        String month = queryVO.getYearMonth().substring(4, 6);
        map.put("weeks", calendarService.weekListByMonth(year, month));
        OtdOrderCirVO data = new OtdOrderCirVO();
        data.setTotal(baseMapper.findMonthCirWeeklyCount(map));
        data.setList(baseMapper.findMonthCirWeekly(map));
        return data;
    }

    /**
     * 根据年月查询待反馈CIR订单数量
     *
     * @param yearMonths 年月
     */
    @Override
    public int findWaitCirOrderCountByYearMonth(List<String> yearMonths) {
        return baseMapper.selectWaitCirOrderCountByYearMonth(yearMonths);
    }

    /**
     * 根据年月删除CIR订单
     *
     * @param year 年
     * @param weeks 周
     */
    @Override
    public void deleteCirOrderByYearWeeks(String year, List<String> weeks) {
        baseMapper.deleteCirOrderByYearWeeks(year, weeks);
    }

    /**
     * 生成月计划接口JSON
     *
     * @param orderList 待发送CIR
     * @return JSON
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String generateSapJson(List<OtdOrderCir> orderList) {
//        ////// 约束条件
//        List<VehicleConfigConstraint> constraintsDB = configConstraintService.findEnableConfigConstraint();
//        if (CollectionUtils.isEmpty(constraintsDB)) {
//            throw new RuntimeException("未维护约束关系");
//        }
        ////// 约束条件
        Map<String, List<VehicleConfigConstraint>> constraintsMap = configConstraintService
            .findEnableConfigConstraintMap();

        ////// 全量工程配置
        // 全量工程配置 MAP,<key:特征值,value:特征族>
        Map<String, String> allConfigMap = biz2baseVehicleConfigDubboService.loadAllEngineeringConfig();

        //月计划编号
        String planNO = code.createCode("MP", "yyMMdd", 5);

        //月计划数据
        List<MonthPlanVO> orders = new ArrayList<>();
        //选装包list
        List<OtdModelVO> packages = new ArrayList<>();

        // 配置识别码初始化
        String timestamp = String.valueOf(new Date().getTime());
        int initPackageNo = 10000;
        // packageNoMap: 记录已添加的工程配置
        Map<String, String> packageNoMap = new HashMap<>();
//        packageNoMap.put("", "10000");

        // 行项目编号
        int itemNo = 10;
        for (OtdOrderCir order : orderList) {
            if (order.getOrderNum() == 0) {
                continue;
            }
            //////月计划编号，发送SAP时统一一个
            order.setPlanNo(planNO);
            order.setSapState("W");
            order.setUpdateBy("月计划接口");
            order.setUpdateTime(new Date());

//            //车配置
//            String packageCode = "";
//            String key;
//            if (StringUtils.isEmpty(order.getCustomPackCode())) {
//                // 选装包为空取默认10000
//                key = "";
//            } else {
//                packageCode = order.getCustomPackCode();
//                // 产品编码 + 选装包
//                key = order.getProductCode() + packageCode;
//            }

            //车配置
            String packageCode = StringUtils.isEmpty(order.getCustomPackCode()) ? "" : order.getCustomPackCode();
            // 产品编码 + 选装包
            String key = order.getProductCode() + packageCode;

            //校验是否已添加相同配置
            if (packageNoMap.get(key) == null) {
                initPackageNo ++;
//                packageNo = initPackageNo;
                packageNoMap.put(key, timestamp + initPackageNo);

                /// 单车默认配置MAP,<key:特征族,value:特征值>
                Map<String, String> configMap = biz2baseVehicleConfigDubboService
                    .loadEngineeringConfigByVehicleCode(order.getCatalogCode(), order.getColorCodeIn(),
                        order.getColorCodeOut(), packageCode, allConfigMap);

                //// =======1.工程配置
                List<VehicleConfigConstraint> constraintList = constraintsMap.get(order.getModelCode());
                if(!CollectionUtils.isEmpty(constraintList)){
                    for (VehicleConfigConstraint constraint : constraintList) {
                        constraint.setIsProcess(0);
                    }
                    /////// 根据约束关系调整默认工程配置 ///////
                    configConstraintService.replaceConfig(constraintList, configMap, allConfigMap);
                }
                List<OtdModelVO> modelVOS = OtdModelVO
                    .createModelVO(configMap, packageNoMap.get(key), order.getCatalogCode());
                packages.addAll(modelVOS);
            }

            //// =======2.订单数据
            MonthPlanVO planVO = createInterfaceData(order, String.valueOf(itemNo), packageNoMap.get(key));
            orders.add(planVO);
            // 行项目编号增加
            itemNo += 10;

        }

        // 批量更新接口状态、操作人、操作时间
        updateBatchById(orderList);

        //// 接口对象转JSON字符串
        MonthPlanDataVO dataVO = new MonthPlanDataVO();
        dataVO.setOrders(orders);
        dataVO.setPackages(packages);
        return JSONObject.toJSONString(dataVO);
    }

    /**
     * 创建接口数据
     *
     * @param order CIR
     * @param itemNo 行项目编号
     * @param packageNo 配置识别码
     * @return MonthPlanVO
     */
    private MonthPlanVO createInterfaceData(OtdOrderCir order, String itemNo, String packageNo) {
        //创建接口传输对象
        MonthPlanVO plan = new MonthPlanVO();
        // plan.setPackage_no();
        plan.setCar_model(order.getCatalogCode());
        //plan.setCar_model("AM861BFMCHL19B0");
        plan.setItem_no(String.valueOf(itemNo));
        plan.setPlanno(order.getPlanNo());
        plan.setStart_date(DateUtil.format(order.getDemandDate(), "yyyy-MM-dd"));
        plan.setWerks(order.getWorks());
        plan.setQty(String.valueOf(order.getOrderNum()));
        plan.setPackage_no(packageNo);
        return plan;
    }


    /**
     * SAP反馈，更新状态
     * @param planNo 生产计划号
     * @param sapNo SAP单号
     * @param sapState SAP状态
     * @param errorInfo 异常信息
     */
    @Override
    public void updateIfPlanBySapBack(String planNo, String sapNo, String sapState, String errorInfo) {
        baseMapper.updateIfPlanBySapBack(planNo, sapNo, sapState, errorInfo);
    }
}
